package cn.acewill.yxd.yunxundian.pubClass;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.http.app.ResponseParser;
import org.xutils.http.request.UriRequest;
import org.xutils.x;

import java.io.File;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.model.RMain;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.rJson;
import cn.acewill.yxd.yunxundian.model.sType;
import cn.acewill.yxd.yunxundian.model.tempLostRR;

import static android.content.Context.MODE_PRIVATE;

/**
 * Created by he on 2017/3/23.
 */

public class pubClass {

    public static String HTTP="http://";
    public static String SecondIP ="";
    public static String SERVER_NAME="/appservice/appservicehzm.aspx";

    //默认服务器配置检测网络路径
    public static String checkUrl = "http://yxd.acewill.cn/dev/appservice/appservicehzm.aspx";
    //h5评估查看页面
//    public static String Server_rv="http://yxd.acewill.cn/dev/system/reportView.aspx?schid=";
    //通用网络请求地址
    public static String Server_namehzm;
    //图片，视屏下载地址
    public static String downLoadUri;
    //图片头像拍摄保存的路径
    public  static String pictureSavePath= Environment.getExternalStorageDirectory()
            +"/"+"cn.acewill.yxd"+"/files/pictures/";
    //用户拍摄视频保存的路径
    public  static String videoSavePath= Environment.getExternalStorageDirectory()
            +"/"+"cn.acewill.yxd"+"/files/Video/";
    public static String videoDownLoadPath =Environment.getExternalStorageDirectory().getPath() + File.separator
            +"/cn.acewill.yxd/downloads/files/video/";
    //获取apk版本信息.text路径
    public static String apkVersionInfoUrl = "http://yxd.acewill.cn/dev/apk.txt";
//    //用户下载保存的图片路径
//    public static String pictureDownloadUri = Environment.getExternalStorageDirectory().getPath() + File.separator
//            +"/cn.acewill.yxd/downloads/pictures";
//    //用户下载视屏保存的路径
//    public static String videoDownloadUri = Environment.getExternalStorageDirectory().getPath() + File.separator
//            +"/cn.acewill.yxd/downloads/video";
    //保存工具箱即文件的路径
    public static String wordPdfUri = Environment.getExternalStorageDirectory().getPath() + File.separator
            +"/cn.acewill.yxd/downloads/files/";
    //apk存放路径
    public static String saveApkUrl = Environment.getExternalStorageDirectory()+ File.separator
            +"/"+"cn.acewill.yxd"+"/downloads/云巡店.apk";
    //查看报表的路径
    public static String Server_lookReport = "";
    //查看管理效率
    public static String Effic_Server = "";
    //请求dialog
    public static ProgressDialog dialog=null;
   // public  static String URL="http://yxd.acewill.cn/dev/";
    public static int scal=4;
    //评估编辑是否提示评分说明缓存文件路径
    public  static String CachePath = Environment.getExternalStorageDirectory()+"/"+"cn.acewill.yxd"+"/cache/";
    public static String CacheName = "checkCache";
    //视频直播 0 打开，1不打开
    public static int  isEZplayVisible=0;

    public static HashMap<Integer,String> tableScore = new HashMap<>();

    @Nullable
    public static String convertToArrayJson(String jsonStr)
    {
        String[] jsonAll=jsonStr.split("\\|");
        if(jsonAll.length==4)
        {
            if(jsonAll[3].charAt(0)=='{')
                jsonAll[3]="["+jsonAll[3]+"]";
            return jsonAll[3];
        }
        else
            return null;
    }

    public static void  seturl(Context context){
        SharedPreferences sp = context.getSharedPreferences("yxdUrl",MODE_PRIVATE);

        //String name = "192.168.2.102";
        //String branchName ="yxd";

        String name =sp.getString("IpName","");
        String branchName = sp.getString("branchName","");
        Server_namehzm = HTTP+name+"/"+branchName+SERVER_NAME;
        downLoadUri = HTTP+name+"/"+branchName+"/reportimg/";
        SecondIP = HTTP+name+"/"+branchName;
        String lookReport_End = "/system/reportView.aspx?";
        Server_lookReport = HTTP+name+"/"+branchName+ lookReport_End;
        String eff_ServerEnd = "/PAD/manage/selectManagerMain.aspx?deviceEmpid=";
        Effic_Server = HTTP+name+"/"+branchName+ eff_ServerEnd;
        Log.e("Server_namehzm",Server_namehzm);
        Log.e("Effic_Server",Effic_Server);
    }

    public static String convertToArrayJsonNormal(String jsonStr)
    {
        if(jsonStr.equals(""))
        {
            return "[]";
        }
        if(jsonStr.charAt(0)=='{')
            jsonStr="["+jsonStr+"]";
        return jsonStr;
    }

    public static void setDialog(ProgressDialog dialog){
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode==KeyEvent.KEYCODE_SPACE){
                    return true;
                }else{
                    return false;
                }
            }
        });
        dialog.setCancelable(false);
    }


    public static <T> Callback.Cancelable Get(String url, Map<String,String> map, Callback.CommonCallback<T> callback){

        RequestParams params=new RequestParams(url);
        //params.setSslSocketFactory(...); // 设置ssl
        if(null!=map){
            for(Map.Entry<String, String> entry : map.entrySet()){
                params.addQueryStringParameter(entry.getKey(), entry.getValue());
            }
        }
        Callback.Cancelable cancelable = x.http().get(params, callback);
        return cancelable;//test1
    }

    /**
     * 发送post请求
     * @param <T>
     */
    public static <T> Callback.Cancelable Post(String url, Map<String,Object> map, Callback.CommonCallback<T> callback){
        RequestParams params=new RequestParams(url);
        params.setConnectTimeout(10000);
        if(null!=map){
            for(Map.Entry<String, Object> entry : map.entrySet()){
                params.addParameter(entry.getKey(), entry.getValue());
            }
        }
        Callback.Cancelable cancelable = x.http().post(params, callback);
        return cancelable;
    }
/*
    public static <T> void PostSync(String url, Map<String,Object> map,String result)
    {
        RequestParams params=new RequestParams(url);
        if(null!=map){
            for(Map.Entry<Stri, Object> entry : map.entrySet()){
                params.addParameter(entry.getKey(), entry.getValue());
            }
        }
        x.http().postSync(params,result);

    }*/

    public static <T> Callback.Cancelable Post(Context context,String url, Map<String,Object> map, Callback.CommonCallback<T> callback){
        dialog=new ProgressDialog(context);
        setDialog(dialog);
        dialog.setMessage("正在加载");
        if(!dialog.isShowing()){
            dialog.show();
        }
        RequestParams params=new RequestParams(url);
        params.setConnectTimeout(10000);
        if(null!=map){
            for(Map.Entry<String, Object> entry : map.entrySet()){
                params.addParameter(entry.getKey(), entry.getValue());
            }
        }
        Callback.Cancelable cancelable = x.http().post(params, callback);

        return cancelable;
    }

    /**
     * 上传文件
     * @param <T>
     */
    public static <T> Callback.Cancelable UpLoadFile(Context context,String url, Map<String,Object> map, Callback.CommonCallback<T> callback){
        dialog=new ProgressDialog(context);
        setDialog(dialog);
        dialog.setMessage("正在上传");
        if(!dialog.isShowing()){
            dialog.show();
        }

        RequestParams params=new RequestParams(url);
        if(null!=map){
            for(Map.Entry<String, Object> entry : map.entrySet()){
                params.addParameter(entry.getKey(), entry.getValue());
            }
        }
        params.setMultipart(true);
        Callback.Cancelable cancelable = x.http().post(params, callback);
        return cancelable;
    }

    public static <T> Callback.Cancelable UpLoadFile(String url, Map<String,Object> map, Callback.CommonCallback<T> callback){
        RequestParams params=new RequestParams(url);
        if(null!=map){
            for(Map.Entry<String, Object> entry : map.entrySet()){
                params.addParameter(entry.getKey(), entry.getValue());
            }
        }
        params.setMultipart(true);
        Callback.Cancelable cancelable = x.http().post(params, callback);
        return cancelable;
    }

    /**
     * 下载文件
     * @param <T>
     */
    public static <T> Callback.Cancelable DownLoadFile(String url,String filepath, Callback.ProgressCallback<File> callback) {
        RequestParams params = new RequestParams(url);
        //设置断点续传
        params.setAutoResume(false);
        params.setAutoRename(false);
        params.setCancelFast(true);

        params.setSaveFilePath(filepath);
        Callback.Cancelable cancelable = x.http().get(params, callback);
        return cancelable;
    }

    public class JsonResponseParser implements ResponseParser {
        //检查服务器返回的响应头信息
        @Override
        public void checkResponse(UriRequest request) throws Throwable {
        }

        /**
         * 转换result为resultType类型的对象
         *
         * @param resultType  返回值类型(可能带有泛型信息)
         * @param resultClass 返回值类型
         * @param result      字符串数据
         * @return
         * @throws Throwable
         */
        @Override
        public Object parse(Type resultType, Class<?> resultClass, String result) throws Throwable {
            return new Gson().fromJson(result, resultClass);

        }
    }

    public static class MyCallBack<ResultType> implements Callback.CommonCallback<ResultType>{

        @Override
        public void onSuccess(ResultType result) {
            //可以根据公司的需求进行统一的请求成功的逻辑处理
            if(dialog!=null)
            dialog.dismiss();
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            //可以根据公司的需求进行统一的请求网络失败的逻辑处理
            if(dialog!=null)
            dialog.dismiss();
        }

        @Override
        public void onCancelled(CancelledException cex) {
            if(dialog!=null)
            dialog.dismiss();
        }

        @Override
        public void onFinished() {
            if(dialog!=null)
                dialog.dismiss();
        }
    }

    public static void showToast(String message,Context tempC) {
        Toast toast = Toast.makeText(tempC, message, Toast.LENGTH_SHORT);
        View view = LayoutInflater.from(tempC).inflate(
                R.layout.system_toast_view, null);
        TextView textView = (TextView) view.findViewById(R.id.toastText);

        toast.setView(view);
		/*
		 * 参数1：设置toast弹出框在界面中的对齐方式 参数2：X偏移量 参数3：Y偏移量
		 */
        toast.setGravity(Gravity.CENTER, 0, 0);
        textView.setText(message);

        toast.show();

    }



    static double pi = 3.14159265358979324;
    static double a = 6378245.0;
    static double ee = 0.00669342162296594323;
    public final static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;

    public static double[] wgs2bd(double lat, double lon) {
        double[] wgs2gcj = wgs2gcj(lat, lon);
        double[] gcj2bd = gcj2bd(wgs2gcj[0], wgs2gcj[1]);
        return gcj2bd;
    }

    public static double[] gcj2bd(double lat, double lon) {
        double x = lon, y = lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        double bd_lon = z * Math.cos(theta) + 0.0065;
        double bd_lat = z * Math.sin(theta) + 0.006;
        return new double[] { bd_lat, bd_lon };
    }

    public static double[] bd2gcj(double lat, double lon) {
        double x = lon - 0.0065, y = lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
        double gg_lon = z * Math.cos(theta);
        double gg_lat = z * Math.sin(theta);
        return new double[] { gg_lat, gg_lon };
    }

    public static double[] wgs2gcj(double lat, double lon) {
        double dLat = transformLat(lon - 105.0, lat - 35.0);
        double dLon = transformLon(lon - 105.0, lat - 35.0);
        double radLat = lat / 180.0 * pi;
        double magic = Math.sin(radLat);
        magic = 1 - ee * magic * magic;
        double sqrtMagic = Math.sqrt(magic);
        dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
        dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);
        double mgLat = lat + dLat;
        double mgLon = lon + dLon;
        double[] loc = { mgLat, mgLon };
        return loc;
    }

    private static double transformLat(double lat, double lon) {
        double ret = -100.0 + 2.0 * lat + 3.0 * lon + 0.2 * lon * lon + 0.1 * lat * lon + 0.2 * Math.sqrt(Math.abs(lat));
        ret += (20.0 * Math.sin(6.0 * lat * pi) + 20.0 * Math.sin(2.0 * lat * pi)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lon * pi) + 40.0 * Math.sin(lon / 3.0 * pi)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(lon / 12.0 * pi) + 320 * Math.sin(lon * pi  / 30.0)) * 2.0 / 3.0;
        return ret;
    }

    private static double transformLon(double lat, double lon) {
        double ret = 300.0 + lat + 2.0 * lon + 0.1 * lat * lat + 0.1 * lat * lon + 0.1 * Math.sqrt(Math.abs(lat));
        ret += (20.0 * Math.sin(6.0 * lat * pi) + 20.0 * Math.sin(2.0 * lat * pi)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lat * pi) + 40.0 * Math.sin(lat / 3.0 * pi)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(lat / 12.0 * pi) + 300.0 * Math.sin(lat / 30.0 * pi)) * 2.0 / 3.0;
        return ret;
    }

    public static String calScoreBySch(int schid) throws DbException {
        YXDAPP yxdapp = new YXDAPP();
        DbManager db = x.getDb(yxdapp.getDaoConfig());
        String retStr="";
        int thisTimeFail = 0;
        int countLostPoint = 0;
        BigDecimal trMscore=new BigDecimal(0);
        String trmlevel="";
        Schedule sMain=db.selector(Schedule.class).where("ID", "=", schid+"").findFirst();
        sType type = db.selector(sType.class).where("ID", "=", sMain.getSTypeID()).findFirst();
        rJson rmian = db.selector(rJson.class).where("ID", "=", type.getReportId()).findFirst();
        /*转化的到集合*/
        if (rmian==null){
            return "erro";
        }
        String json = rmian.getjSon();
        Gson gson = new Gson();
        Type typeList = new TypeToken<ArrayList<RMain>>() {
        }.getType();
        //拿到所有评估项集合后

        ArrayList<RMain> rMains = gson.fromJson(pubClass.convertToArrayJsonNormal(json), typeList);
        List<RMain.TablesBean> tables=rMains.get(0).getTables();

        switch (rMains.get(0).getQ().getCountFunc()){
            case 1:{
                retStr = cal1(schid);
                break;
            }
            case 2:{
                retStr = cal1(schid);
                break;
            }
            case 3:{
                retStr = cal3(schid);
                break;
            }
            default:{
                retStr = cal1(schid);
                break;
            }
        }


        return retStr;
    }

    public static String cal1( int schid) throws DbException{
        tableScore = new HashMap<>();
        HashMap<Integer,BigDecimal> tScore = new HashMap<>();
        YXDAPP yxdapp = new YXDAPP();
        DbManager db = x.getDb(yxdapp.getDaoConfig());
        String retStr="";
        int thisTimeFail = 0;
        int countLostPoint = 0;
        BigDecimal trMscore=new BigDecimal(0);
        String trmlevel="";
        Schedule sMain=db.selector(Schedule.class).where("ID", "=", schid+"").findFirst();
        sType type = db.selector(sType.class).where("ID", "=", sMain.getSTypeID()).findFirst();
        rJson rmian = db.selector(rJson.class).where("ID", "=", type.getReportId()).findFirst();
        /*转化的到集合*/
        if (rmian==null){
            return "erro";
        }
        String json = rmian.getjSon();
        Gson gson = new Gson();
        Type typeList = new TypeToken<ArrayList<RMain>>() {
        }.getType();
        //拿到所有评估项集合后

        ArrayList<RMain> rMains = gson.fromJson(pubClass.convertToArrayJsonNormal(json), typeList);
        List<RMain.TablesBean> tables=rMains.get(0).getTables();
        BigDecimal zuihoufenzi = new BigDecimal(0);
        BigDecimal zuihoufenmu = new BigDecimal(0);
        //循环查询大项的总分，查找是否存在当前评估项
        for(RMain.TablesBean t:tables)
        {
            BigDecimal reportTableMaxScoreFenmu = new BigDecimal(t.getQ1().getScore());//大项总分
            BigDecimal reportTableMaxScoreFenzi = new BigDecimal(t.getQ1().getScore());//大项总分
            int maxPointNum = t.getQ1().getPointNum();//大项关键项总分
            int nowPointNum = 0;
            int thisLostItem = 0;
            List<RMain.TablesBean.RowsBean> reportRowQ=t.getRows();
            for(RMain.TablesBean.RowsBean r:reportRowQ)
            {
                List<tempLostRR> listRR=db.selector(tempLostRR.class)
                        .where("schId","=",sMain.getID()+"")
                        .and("rRowId","=",r.getQ2().getID()+"")
                        .findAll();
                //存在当前评估项则进入计算
                if(listRR!=null && listRR.size()>0)
                {
                    BigDecimal thistempLostScore=new BigDecimal(0);
                    for(tempLostRR trr:listRR)
                    {
                        //找到ritem,取出评数据
                        RMain.TablesBean.RowsBean.RItemsBean ri=getItemsByItemsID(trr.getSelectItemId(),trr.getRRowId(),rMains);
                        BigDecimal riScore=new BigDecimal(0);
                        if(ri==null)
                        {
//                            return trr.getRowName()+"有错请检查其选项";
                            return "erro";
                        }
                        //此项是无评分选项，直接rr取
                        if(r.getQ2().getItemType()==2)
                            riScore=new BigDecimal(trr.getScore());
                        else
                            riScore=new BigDecimal(ri.getScore());
                        if(riScore!=BigDecimal.valueOf (r.getQ2().getMaxScore()))//失分项
                        {
                            if(riScore==BigDecimal.valueOf(-1)) {//n/a项
                                reportTableMaxScoreFenmu = reportTableMaxScoreFenmu.subtract(BigDecimal.valueOf(r.getQ2().getMaxScore())
                                        .multiply(BigDecimal.valueOf(r.getQ2().getRights())));
                                reportTableMaxScoreFenzi = reportTableMaxScoreFenzi.subtract(BigDecimal.valueOf(r.getQ2().getMaxScore())
                                        .multiply(BigDecimal.valueOf(r.getQ2().getRights())));
                            }
                            else{
                                BigDecimal thisMax= new BigDecimal(r.getQ2().getMaxScore());
                                if(r.getQ2().getItemType()==0||r.getQ2().getItemType()==1)
                                {
                                    List<RMain.TablesBean.RowsBean.RItemsBean> tempitemlist=getItemsByRrowid(trr.getRRowId(),rMains);
                                    double tempmax=-1000;
                                    for(RMain.TablesBean.RowsBean.RItemsBean rib:tempitemlist)
                                    {
                                        //第一个是最高分
                                        if(rib.getScore()>tempmax)
                                            tempmax=rib.getScore();
                                    }
                                    //就是Q2的最大分数
                                    if(tempmax!=-1000)
                                        thisMax=BigDecimal.valueOf(tempmax);
                                }
                                //计算当前的分数据
                                thistempLostScore=thistempLostScore.add(thisMax.subtract(BigDecimal.valueOf(trr.getScore())));
                                //tRR.scoreLostItem = 1;
                                //tRR.score = riScore * r.rights;
                                //bkData.SubmitChanges();
                                thisLostItem+=1;
                                if(r.getQ2().getIsPoint()==1)
                                    nowPointNum+=1;
                            }
                            if(thistempLostScore.compareTo(BigDecimal.valueOf(r.getQ2().getMaxScore()))!=-1)
                            {
                                reportTableMaxScoreFenzi=reportTableMaxScoreFenzi.subtract(BigDecimal.valueOf(r.getQ2().getMaxScore())
                                        .multiply(BigDecimal.valueOf(r.getQ2().getRights())));
                            }
                            else{
                                //只会进入此方法，用大项的总分减去当前的失分项
                                reportTableMaxScoreFenzi=reportTableMaxScoreFenzi.subtract(thistempLostScore.multiply(BigDecimal.valueOf(r.getQ2().getRights())));
                            }

                        }

                    }
                }
            }
            BigDecimal tRTscorefenmu = reportTableMaxScoreFenmu;
            BigDecimal tRTscorefenzi = reportTableMaxScoreFenzi;
            if(tRTscorefenzi.compareTo(BigDecimal.valueOf(0))==-1)
                tRTscorefenzi=BigDecimal.valueOf(0);
//            if(reportTableMaxScoreFenmu.compareTo(BigDecimal.valueOf(0))==1)
//                tRTscore=BigDecimal.valueOf(100).multiply(reportTableMaxScoreFenzi.divide(reportTableMaxScoreFenmu));
//            else
//                tRTscore=new BigDecimal(100);
            if(t.getQ1().getIsInScore()!=0)
            {
                zuihoufenzi=zuihoufenzi.add(tRTscorefenzi.multiply(BigDecimal.valueOf(t.getQ1().getRights())));
                zuihoufenmu=zuihoufenmu.add(tRTscorefenmu.multiply(BigDecimal.valueOf(t.getQ1().getRights())));
                countLostPoint = countLostPoint + thisLostItem;
            }

            tScore.put(t.getQ1().getID(),tRTscorefenzi.multiply(BigDecimal.valueOf(t.getQ1().getRights())));

            if(nowPointNum >= maxPointNum && maxPointNum != 0)
            {
                thisTimeFail=1;
            }
        }
        if(zuihoufenzi.compareTo(BigDecimal.valueOf(0))==0 &&zuihoufenmu.compareTo(BigDecimal.valueOf(0))==0)
        {
            zuihoufenzi=new BigDecimal(100);
            zuihoufenmu=new BigDecimal(100);
        }
        trMscore=BigDecimal.valueOf(100).multiply(zuihoufenzi.divide(zuihoufenmu,scal,BigDecimal.ROUND_HALF_EVEN));

        for (Integer key : tScore.keySet()) {
            BigDecimal tempScore = tScore.get(key);
            tempScore = BigDecimal.valueOf(100).multiply(tempScore.divide(zuihoufenmu,scal,BigDecimal.ROUND_HALF_EVEN));
            tableScore.put(key,tempScore.toString());
        }

        if(thisTimeFail!=1)
            trmlevel=getLevel(trMscore,rMains.get(0).getQ().getLevelJSON(),countLostPoint);
        else
            trmlevel=getXianjinLevel(rMains.get(0).getQ().getLevelJSON(),"F");
        trMscore=trMscore.setScale(2,BigDecimal.ROUND_HALF_EVEN);
        retStr=trMscore.toString()+"("+trmlevel+")";
        return retStr;
    }

    protected static String cal3(int schid) throws DbException{
        tableScore = new HashMap<>();
        HashMap<Integer,BigDecimal> tScore = new HashMap<>();
        YXDAPP yxdapp = new YXDAPP();
        DbManager db = x.getDb(yxdapp.getDaoConfig());
        String retStr="";
        int thisTimeFail = 0;
        int countLostPoint = 0;
        BigDecimal trMscore=new BigDecimal(0);
        String trmlevel="";
        Schedule sMain=db.selector(Schedule.class).where("ID", "=", schid+"").findFirst();
        sType type = db.selector(sType.class).where("ID", "=", sMain.getSTypeID()).findFirst();
        rJson rmian = db.selector(rJson.class).where("ID", "=", type.getReportId()).findFirst();
        /*转化的到集合*/
        if (rmian==null){
            return "erro";
        }
        String json = rmian.getjSon();
        Gson gson = new Gson();
        Type typeList = new TypeToken<ArrayList<RMain>>() {
        }.getType();
        //拿到所有评估项集合后

        ArrayList<RMain> rMains = gson.fromJson(pubClass.convertToArrayJsonNormal(json), typeList);
        List<RMain.TablesBean> tables=rMains.get(0).getTables();
        BigDecimal zuihoufenzi = new BigDecimal(0);
        BigDecimal zuihoufenmu = new BigDecimal(0);
        //循环查询大项的总分，查找是否存在当前评估项
        for(RMain.TablesBean t:tables)
        {
            BigDecimal reportTableMaxScoreFenmu = new BigDecimal(t.getQ1().getScore());//大项总分
            BigDecimal reportTableMaxScoreFenzi = BigDecimal.ZERO;//大项扣总分
            int maxPointNum = t.getQ1().getPointNum();//大项关键项总分
            int nowPointNum = 0;
            int thisLostItem = 0;
            List<RMain.TablesBean.RowsBean> reportRowQ=t.getRows();
            for(RMain.TablesBean.RowsBean r:reportRowQ)
            {
                List<tempLostRR> listRR=db.selector(tempLostRR.class)
                        .where("schId","=",sMain.getID()+"")
                        .and("rRowId","=",r.getQ2().getID()+"")
                        .findAll();
                //存在当前评估项则进入计算
                if(listRR!=null && listRR.size()>0)
                {
                    BigDecimal thistempLostScore=new BigDecimal(0);
                    for(tempLostRR trr:listRR)
                    {
                        //找到ritem,取出评数据
                        RMain.TablesBean.RowsBean.RItemsBean ri=getItemsByItemsID(trr.getSelectItemId(),trr.getRRowId(),rMains);
                        BigDecimal riScore=new BigDecimal(0);
                        if(ri==null)
                        {
//                            return trr.getRowName()+"有错请检查其选项";
                            return "erro";
                        }
                        //此项是无评分选项，直接rr取
                        if(r.getQ2().getItemType()==2)
                            riScore=new BigDecimal(trr.getScore());
                        else
                            riScore=new BigDecimal(ri.getScore());
                        if(riScore!=null)//失分项
                        {
                            if(riScore==BigDecimal.valueOf(-1)) {//n/a项
                                reportTableMaxScoreFenmu = reportTableMaxScoreFenmu.subtract(BigDecimal.valueOf(r.getQ2().getMaxScore())
                                        .multiply(BigDecimal.valueOf(r.getQ2().getRights())));
                                reportTableMaxScoreFenzi = reportTableMaxScoreFenzi.subtract(BigDecimal.valueOf(r.getQ2().getMaxScore())
                                        .multiply(BigDecimal.valueOf(r.getQ2().getRights())));
                            }
                            else{
//                                BigDecimal thisMax= new BigDecimal(r.getQ2().getMaxScore());
//                                if(r.getQ2().getItemType()==0||r.getQ2().getItemType()==1)
//                                {
//                                    List<RMain.TablesBean.RowsBean.RItemsBean> tempitemlist=getItemsByRrowid(trr.getRRowId(),rMains);
//                                    double tempmax=-1000;
//                                    for(RMain.TablesBean.RowsBean.RItemsBean rib:tempitemlist)
//                                    {
//                                        //第一个是最高分
//                                        if(rib.getScore()>tempmax)
//                                            tempmax=rib.getScore();
//                                    }
//                                    //就是Q2的最大分数
//                                    if(tempmax!=-1000)
//                                        thisMax=BigDecimal.valueOf(tempmax);
//                                }
                                //计算当前的分数据
                                thistempLostScore=thistempLostScore.add(riScore);
                                //tRR.scoreLostItem = 1;
                                //tRR.score = riScore * r.rights;
                                //bkData.SubmitChanges();
                                thisLostItem+=1;
                                if(r.getQ2().getIsPoint()==1)
                                    nowPointNum+=1;
                            }
                            if(thistempLostScore.compareTo(BigDecimal.valueOf(r.getQ2().getMaxScore()))!=-1)
                            {
                                //reportTableMaxScoreFenzi=reportTableMaxScoreFenzi.subtract(BigDecimal.valueOf(r.getQ2().getMaxScore()).multiply(BigDecimal.valueOf(r.getQ2().getRights())));
                                reportTableMaxScoreFenzi=reportTableMaxScoreFenzi.add(thistempLostScore.multiply(BigDecimal.valueOf(r.getQ2().getRights())));
                            }
                            else{
                                reportTableMaxScoreFenzi=reportTableMaxScoreFenzi.add(thistempLostScore.multiply(BigDecimal.valueOf(r.getQ2().getRights())));
                            }

                        }

                    }
                    if(reportTableMaxScoreFenzi.compareTo(reportTableMaxScoreFenmu)==1)
                    {
                        reportTableMaxScoreFenzi = reportTableMaxScoreFenmu;
                    }



                }
            }
            BigDecimal tRTscorefenmu = reportTableMaxScoreFenmu;
            BigDecimal tRTscorefenzi = reportTableMaxScoreFenzi;
            if(tRTscorefenzi.compareTo(BigDecimal.valueOf(0))==-1)
                tRTscorefenzi=BigDecimal.valueOf(0);
//            if(reportTableMaxScoreFenmu.compareTo(BigDecimal.valueOf(0))==1)
//                tRTscore=BigDecimal.valueOf(100).multiply(reportTableMaxScoreFenzi.divide(reportTableMaxScoreFenmu));
//            else
//                tRTscore=new BigDecimal(100);
            if(t.getQ1().getIsInScore()!=0)
            {
                zuihoufenzi=zuihoufenzi.add(tRTscorefenzi.multiply(BigDecimal.valueOf(t.getQ1().getRights())));
                zuihoufenmu=zuihoufenmu.add(tRTscorefenmu.multiply(BigDecimal.valueOf(t.getQ1().getRights())));
                countLostPoint = countLostPoint + thisLostItem;
            }
            if(nowPointNum >= maxPointNum && maxPointNum != 0)
            {
                thisTimeFail=1;
            }

            tScore.put(t.getQ1().getID(),tRTscorefenmu.subtract(tRTscorefenzi).multiply(BigDecimal.valueOf(t.getQ1().getRights())));

        }
        if(zuihoufenzi.compareTo(BigDecimal.valueOf(0))==0 &&zuihoufenmu.compareTo(BigDecimal.valueOf(0))==0)
        {
            zuihoufenzi=new BigDecimal(100);
            zuihoufenmu=new BigDecimal(100);
        }
        trMscore=BigDecimal.valueOf(100).multiply(zuihoufenmu.subtract(zuihoufenzi).divide(zuihoufenmu,scal,BigDecimal.ROUND_HALF_EVEN));
        for (Integer key : tScore.keySet()) {
            BigDecimal tempScore = tScore.get(key);
            tempScore = BigDecimal.valueOf(100).multiply(tempScore.divide(zuihoufenmu,scal,BigDecimal.ROUND_HALF_EVEN));
            tableScore.put(key,tempScore.toString());
        }
        //Log.e("ababababab",tScore);
        //Log.e("ababababab",tableScore);
        //System.out(tableScore);
        if(thisTimeFail!=1)
            trmlevel=getLevel(trMscore,rMains.get(0).getQ().getLevelJSON(),countLostPoint);
        else
            trmlevel=getXianjinLevel(rMains.get(0).getQ().getLevelJSON(),"F");
        trMscore=trMscore.setScale(2,BigDecimal.ROUND_HALF_EVEN);
        retStr=trMscore.toString()+"("+trmlevel+")";
        return retStr;
    }

    protected static String getXianjinLevel(String levelStr, String yuanLevel)
    {
        if (levelStr.contains("item"))
        {
            levelStr = levelStr.substring(5);
            String[] levels = levelStr.split(";");
            String[] sp = levels[levels.length - 1].split("-");
            return sp[0];
        }
        else
        {
            String[] levels = levelStr.split(";");
            if (levels.length > 0)
            {
                String[] sp = levels[levels.length - 1].split("-");
                return sp[0];
            }
        }
        return yuanLevel;
    }

    protected static String getLevel(BigDecimal score, String levelStr, int lostItemCount)
    {
        if (levelStr.contains("item"))
        {
            levelStr = levelStr.substring(5);
            String[] levels = levelStr.split(";");
            for (String item : levels)
            {
                String[] sp = item.split("-");
                if (Integer.valueOf(sp[1]) <= lostItemCount && lostItemCount <= Integer.valueOf(sp[2]))
                    return sp[0];
            }
            return "Z";
        }
        else
        {
            String[] levels = levelStr.split(";");
            for (String item : levels)
            {
                String[] sp = item.split("-");
                if(score.compareTo(BigDecimal.valueOf(Double.valueOf(sp[1])))==1&&(!(score.compareTo(BigDecimal.valueOf(Double.valueOf(sp[2])))==1)))
                    return sp[0];
            }
            return "Z";
        }
    }

    private static List<RMain.TablesBean.RowsBean.RItemsBean> getItemsByRrowid(int rowid, ArrayList<RMain> rMains) {
        List<RMain.TablesBean.RowsBean.RItemsBean> itemList = null;
        for (int i = 0; i < rMains.size(); i++) {
            List<RMain.TablesBean> tb = rMains.get(i).getTables();
            for (RMain.TablesBean t : tb) {
                List<RMain.TablesBean.RowsBean> rbs = t.getRows();
                for (RMain.TablesBean.RowsBean rb : rbs) {
                    if (rb.getQ2().getID() == rowid) {
                        itemList = rb.getRItems();
                        break;
                    }
                }
            }
        }
        return itemList;
    }

    //查询出ritem
    private static RMain.TablesBean.RowsBean.RItemsBean getItemsByItemsID(int itemid, int rowid, ArrayList<RMain> rMains)
    {
        RMain.TablesBean.RowsBean.RItemsBean retRIB=null;
        List<RMain.TablesBean.RowsBean.RItemsBean> tempItems=getItemsByRrowid(rowid,rMains);
        if(tempItems!=null)
        {
            for(RMain.TablesBean.RowsBean.RItemsBean irb:tempItems)
            {
                if(itemid==0)
                {
                    retRIB=irb;
                }
                if(irb.getID()==itemid) {
                retRIB = irb;
                break;
            }
            }
        }
        return retRIB;
    }

    private double getMaxScoreByRrowid(int rowid, ArrayList<RMain> rMains) {
        double maxscore = 0;
        for (int i = 0; i < rMains.size(); i++) {
            List<RMain.TablesBean> tb = rMains.get(i).getTables();
            for (RMain.TablesBean t : tb) {
                List<RMain.TablesBean.RowsBean> rbs = t.getRows();
                for (RMain.TablesBean.RowsBean rb : rbs) {
                    if (rb.getQ2().getID() == rowid) {
                        maxscore = rb.getQ2().getMaxScore();
                        break;
                    }
                }
            }
        }
        return maxscore;
    }

}




